<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-07-26 09:54
 *
 * Version: 2.0
 */

namespace App\Modules\Message\Criterias;

use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;

class GetWxMessageListCriteria extends BaseCriterias
{
	private $params;

	public function __construct($recipient, $scene, $type=null,$isCount=false,$isApp=false,$storeId=null)
	{
		$this->params = [
			'type'      => (($scene == config('constant.message.scene.wx')) || empty($type))  ? array_values(config('constant.message.type')) : [$type],
			'recipient' => $recipient,
			'scene'     => empty($scene) ? config('constant.message.scene.wx') : $scene,
			'count' => $isCount,
			'is_app' => $isApp,
			'store_id' =>$storeId
		];
	}

	public function apply($model, RepositoryInterface $repository)
	{
		$type = $this->params['type'];
		$isApp = $this->params['is_app'];
		$map = [
			'scene'     => $this->params['scene'],
			'recipient' => $this->params['recipient'],
		];
		if(isset($this->params['store_id'])) $map['store_id'] = $this->params['store_id'];

			return $this->params['count'] ? $model->selectRaw('count(id) as count,is_read')
				->with([
					'message' => function ($query) use ($type,$isApp) {
						$query->whereIn('type', $type)->when(!$isApp,function($v){
							$v->where('sub_type','<>',config('constant.message.sub_type.new_order'))->where('sub_type','>',0);
						});
					}
				])
				->where($map)
				->whereNotNull('store_id')
				->groupBy('is_read')
				:
				$model
					->with('message','store:id,name')
					->whereHas(
						'message', function ($query) use ($type,$isApp) {
						$query->whereIn('type', $type)->when(!$isApp,function($v){
							$v->where('sub_type','<>',config('constant.message.sub_type.new_order'))->where('sub_type','>',0);
						});
					}
					)
					->where($map)
					->orderBy('id','desc')
					->orderBy('is_read','asc');
//					->orderBy('message_id','desc');
		}




}
